<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta name="generator" content="Hugo 0.82.1" />
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="[golang] 错误处理#Go 语言的错误处理方式#Go 语言 提供了两种错误处理方式:
 返回错误模式: 函数的返回是一个复合类型，其中一个类型（习惯上是最后一个类型）是 error ，类似于：(, error)。  这种模式被期望处理的场景是：当错误发生的情况下，在处理错误后，程序扔可以继续执行下去。
 中断/恢复模式：panic/recover  中断/恢复模式适用于：当错误发生的情况下，处理错误后，程序无法继续执行下去，需要中断当前的程序或者协程。
error 接口#Go 语言提供了内嵌接口 error，其定义是:
type error interface { Error() string } 因此，任何有 Error() string 方法的类型都可以被认为是 Error 类。
type PathError struct { Op string // &#34;open&#34;, &#34;unlink&#34;, etc. 	Path string // The associated file. } func (e *PathError) Error() string { return e.Op &#43; &#34; &#34; &#43; e.">
<meta name="theme-color" content="#FFFFFF"><meta property="og:title" content="错误处理" />
<meta property="og:description" content="[golang] 错误处理#Go 语言的错误处理方式#Go 语言 提供了两种错误处理方式:
 返回错误模式: 函数的返回是一个复合类型，其中一个类型（习惯上是最后一个类型）是 error ，类似于：(, error)。  这种模式被期望处理的场景是：当错误发生的情况下，在处理错误后，程序扔可以继续执行下去。
 中断/恢复模式：panic/recover  中断/恢复模式适用于：当错误发生的情况下，处理错误后，程序无法继续执行下去，需要中断当前的程序或者协程。
error 接口#Go 语言提供了内嵌接口 error，其定义是:
type error interface { Error() string } 因此，任何有 Error() string 方法的类型都可以被认为是 Error 类。
type PathError struct { Op string // &#34;open&#34;, &#34;unlink&#34;, etc. 	Path string // The associated file. } func (e *PathError) Error() string { return e.Op &#43; &#34; &#34; &#43; e." />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://example.org/docs/erro-handling/" /><meta property="article:section" content="docs" />



<title>错误处理 | My Golang Book</title>
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/favicon.png" type="image/x-icon">
<link rel="stylesheet" href="/book.min.2bc2364a4a4b31f0ec1debecf0a8f90a840821f143dfe1ac6a0f7cbcbdcf64ac.css" integrity="sha256-K8I2SkpLMfDsHevs8Kj5CoQIIfFD3&#43;Gsag98vL3PZKw=">
<script defer src="/en.search.min.84ce9693e6c02d95376f29aeb794c11824d09ed0440f910f008e91e9ed0436e4.js" integrity="sha256-hM6Wk&#43;bALZU3bymut5TBGCTQntBED5EPAI6R6e0ENuQ="></script>
<!--
Made with Book Theme
https://github.com/alex-shpak/hugo-book
-->

  
</head>

<body dir="ltr">
  <input type="checkbox" class="hidden toggle" id="menu-control" />
  <input type="checkbox" class="hidden toggle" id="toc-control" />
  <main class="container flex">
    <aside class="book-menu">
      <div class="book-menu-content">
        
  <nav>
<h2 class="book-brand">
  <a href="/"><span>My Golang Book</span>
  </a>
</h2>


<div class="book-search">
  <input type="text" id="book-search-input" placeholder="Search" aria-label="Search" maxlength="64" data-hotkeys="s/" />
  <div class="book-search-spinner hidden"></div>
  <ul id="book-search-results"></ul>
</div>











  



  
  <ul>
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/introduction/" class="">Golang 介绍</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/installation/" class="">安装、准备开发环境</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/go-routine/" class="">并发处理 - Go 协程</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/workspace-module/" class="">管理Go模块</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/erro-handling/" class=" active">错误处理</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/resources/" class="">Golang 资源</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/statements/" class="">Go For语句</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/guidelines/" class="">Go 开发规范</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/logging/" class="">日志</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/data-init/" class="">Data Init</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/data-types/" class="">Data Types</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/debug/" class="">Debug</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/dynamic-programing/" class="">Dynamic Programing</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/ecosystem/" class="">Ecosystem</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/performance/" class="">Performance</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/struct-interface/" class="">Struct Interface</a>
  

        </li>
      
    
      
        <li>
          
  
  

  
    <a href="http://example.org/docs/struct-tags/" class="">Struct Tags</a>
  

        </li>
      
    
  </ul>















</nav>




  <script>(function(){var a=document.querySelector("aside.book-menu nav");addEventListener("beforeunload",function(b){localStorage.setItem("menu.scrollTop",a.scrollTop)}),a.scrollTop=localStorage.getItem("menu.scrollTop")})()</script>


 
      </div>
    </aside>

    <div class="book-page">
      <header class="book-header">
        
  <div class="flex align-center justify-between">
  <label for="menu-control">
    <img src="/svg/menu.svg" class="book-icon" alt="Menu" />
  </label>

  <strong>错误处理</strong>

  <label for="toc-control">
    
    <img src="/svg/toc.svg" class="book-icon" alt="Table of Contents" />
    
  </label>
</div>


  
  <aside class="hidden clearfix">
    
  
<nav id="TableOfContents">
  <ul>
    <li><a href="#go-语言的错误处理方式">Go 语言的错误处理方式</a></li>
    <li><a href="#error-接口">error 接口</a></li>
    <li><a href="#error-返回处理模式">error 返回/处理模式</a></li>
    <li><a href="#panic-和-recover">panic 和 recover</a></li>
  </ul>
</nav>



  </aside>
  
 
      </header>

      
      
  <article class="markdown"><h1 id="golang-错误处理">
  [golang] 错误处理
  <a class="anchor" href="#golang-%e9%94%99%e8%af%af%e5%a4%84%e7%90%86">#</a>
</h1>
<h2 id="go-语言的错误处理方式">
  Go 语言的错误处理方式
  <a class="anchor" href="#go-%e8%af%ad%e8%a8%80%e7%9a%84%e9%94%99%e8%af%af%e5%a4%84%e7%90%86%e6%96%b9%e5%bc%8f">#</a>
</h2>
<p>Go 语言 提供了两种错误处理方式:</p>
<ul>
<li>返回错误模式: 函数的返回是一个复合类型，其中一个类型（习惯上是最后一个类型）是<code> error</code> ，类似于：<code>(, error)</code>。</li>
</ul>
<p>这种模式被期望处理的场景是：当错误发生的情况下，在处理错误后，程序扔可以继续执行下去。</p>
<ul>
<li>中断/恢复模式：<code>panic/recover</code></li>
</ul>
<p>中断/恢复模式适用于：当错误发生的情况下，处理错误后，程序无法继续执行下去，需要中断当前的程序或者协程。</p>
<h2 id="error-接口">
  error 接口
  <a class="anchor" href="#error-%e6%8e%a5%e5%8f%a3">#</a>
</h2>
<p>Go 语言提供了内嵌接口 <code>error</code>，其定义是:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">type</span> <span style="color:#66d9ef">error</span> <span style="color:#66d9ef">interface</span> {
    <span style="color:#a6e22e">Error</span>() <span style="color:#66d9ef">string</span>
}
</code></pre></div><p>因此，任何有 <code>Error() string</code> 方法的类型都可以被认为是 Error 类。</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">PathError</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Op</span>   <span style="color:#66d9ef">string</span> <span style="color:#75715e">// &#34;open&#34;, &#34;unlink&#34;, etc.
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">Path</span> <span style="color:#66d9ef">string</span> <span style="color:#75715e">// The associated file.
</span><span style="color:#75715e"></span>}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">e</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">PathError</span>) <span style="color:#a6e22e">Error</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">Op</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; &#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">Path</span>
}
</code></pre></div><h2 id="error-返回处理模式">
  error 返回/处理模式
  <a class="anchor" href="#error-%e8%bf%94%e5%9b%9e%e5%a4%84%e7%90%86%e6%a8%a1%e5%bc%8f">#</a>
</h2>
<p>Go 语言中， 当一个错误发生时，希望处理这个错误，然后继续执行。因此默认的错误处理模式是返回包含错误变量的复合结果。</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">returnError</span>() (<span style="color:#a6e22e">ret</span> <span style="color:#66d9ef">interface</span>{}, <span style="color:#a6e22e">err</span> <span style="color:#66d9ef">error</span>) {
	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">PathError</span>{<span style="color:#a6e22e">Op</span>: <span style="color:#e6db74">&#34;open&#34;</span>, <span style="color:#a6e22e">Path</span>: <span style="color:#e6db74">&#34;/root&#34;</span>}
}


<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">returnError</span>()
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#f92672">...</span>
	}

}
</code></pre></div><h2 id="panic-和-recover">
  panic 和 recover
  <a class="anchor" href="#panic-%e5%92%8c-recover">#</a>
</h2>
<p>当错误发生时，程序无法执行下去的时候，这时期望终止程序或者终止当前的协程，在这种情况下，Go 语言提供了内嵌函数 <code>panic</code> 。</p>
<p><code>panic</code> 函数的参数可以是任何类型，一般会使用 <code>string</code>。</p>
<p><code>recover</code> 用于在上层抓住 <code>panic</code> 中的参数，并做适当的处理。</p>
<p>有趣的是，<code>panic()/recover()</code>有点儿像是 <code>try/catch</code>。</p>
<p>示例:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> <span style="color:#e6db74">&#34;fmt&#34;</span>

<span style="color:#75715e">// PathError records an error and the operation and
</span><span style="color:#75715e">// file path that caused it.
</span><span style="color:#75715e"></span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">PathError</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Op</span>   <span style="color:#66d9ef">string</span> <span style="color:#75715e">// &#34;open&#34;, &#34;unlink&#34;, etc.
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">Path</span> <span style="color:#66d9ef">string</span> <span style="color:#75715e">// The associated file.
</span><span style="color:#75715e"></span>}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">e</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">PathError</span>) <span style="color:#a6e22e">Error</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">Op</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34; &#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">Path</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#66d9ef">defer</span> <span style="color:#66d9ef">func</span>() {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">e</span> <span style="color:#f92672">:=</span> recover(); <span style="color:#a6e22e">e</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
			<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">e</span>)
		}
	}()
	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">returnError</span>()
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		panic(<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Error</span>())
	}

}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">returnError</span>() (<span style="color:#a6e22e">ret</span> <span style="color:#66d9ef">interface</span>{}, <span style="color:#a6e22e">err</span> <span style="color:#66d9ef">error</span>) {
	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">PathError</span>{<span style="color:#a6e22e">Op</span>: <span style="color:#e6db74">&#34;open&#34;</span>, <span style="color:#a6e22e">Path</span>: <span style="color:#e6db74">&#34;/root&#34;</span>}
}

</code></pre></div></article>
 
      

      <footer class="book-footer">
        
  <div class="flex flex-wrap justify-between">





</div>

 
        
      </footer>

      
  
  <div class="book-comments">

</div>
  
 

      <label for="menu-control" class="hidden book-menu-overlay"></label>
    </div>

    
    <aside class="book-toc">
      <div class="book-toc-content">
        
  
<nav id="TableOfContents">
  <ul>
    <li><a href="#go-语言的错误处理方式">Go 语言的错误处理方式</a></li>
    <li><a href="#error-接口">error 接口</a></li>
    <li><a href="#error-返回处理模式">error 返回/处理模式</a></li>
    <li><a href="#panic-和-recover">panic 和 recover</a></li>
  </ul>
</nav>


 
      </div>
    </aside>
    
  </main>

  
</body>

</html>












